package com.demo.service;

/**
 * DemoUserService
 *
 * @author liujin
 * @date 2020/12/5 21:24
 */

import com.demo.model.UserDetailDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by macro on 2019/9/30.
 */
@Service
public class DemoUserService implements UserDetailsService {

    private List<UserDetailDemo> userList;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    public void initData() {
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new UserDetailDemo("1","macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"), "departName1"));
        userList.add(new UserDetailDemo("2","andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"), "departName2"));
        userList.add(new UserDetailDemo("3","mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"), "departName3"));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<UserDetailDemo> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(findUserList)) {
            return findUserList.get(0);
        } else {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    }
}